package cc.chinagps.gateway.client.codec;

import cc.chinagps.gateway.client.UnitClient;
import cc.chinagps.gateway.client.UnitClientManager;
import cc.chinagps.gateway.client.bean.PacketType;
import cc.chinagps.gateway.client.bean.ResponseCode;
import cc.chinagps.gateway.client.packet.RequestPacket;
import cc.chinagps.gateway.client.packet.ResponsePacket;
import cc.chinagps.gateway.client.session.ISession;
import cc.chinagps.gateway.common.Config;
import cc.chinagps.gateway.log.LogManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ResponseMessageDecoder extends ByteToMessageDecoder {
    private static final int PACKET_MIN_LENGTH = 1;
    private UnitClient client;

    public ResponseMessageDecoder(UnitClient client) {
        this.client = client;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        ISession session = client.getSession();
        if (session == null) {
            LogManager.t("[{}] client session is null:{}", client.getDeviceInfo().getTerminalNo());
            return;
        }
        if (in.readableBytes() < PACKET_MIN_LENGTH) {
            return;
        }
        session.setLastActiveTime(System.currentTimeMillis());
        ResponsePacket responsePacket = new ResponsePacket();
        responsePacket.decode(in);
        LogManager.t("[{}] recv responsePacket:{}", client.getDeviceInfo().getTerminalNo(), responsePacket);
        client.setCurResponsePacket(responsePacket);
        RequestPacket curRequestPacket = client.getCurRequestPacket();
        if (curRequestPacket != null) {
            PacketType packetType = curRequestPacket.getPacketType();
            if (packetType == PacketType.LOGIN && responsePacket.getData() == ResponseCode.CODEO0.getCode()) {
                long requestPacketCreateTime = curRequestPacket.getCreateTime();
                long responsePacketCreateTime = responsePacket.getCreateTime();
                if (Config.SYS.SUCCESS_MODE == 2 && (responsePacketCreateTime > requestPacketCreateTime) && (responsePacketCreateTime - requestPacketCreateTime) <= Config.SYS.RESPONSE_TIMEOUT) {
                    session.setAuthed(true);
                    client.setReLogin(false);
                }
            }
        }
        out.add(responsePacket);
    }
}
